package com.web.a.weba.filter;


import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Activate(group = {Constants.CONSUMER},order = -2000)
public class TimeRankFilter implements Filter {

    public static Map<String,List<Long>> timeRecoredMap=new ConcurrentHashMap<>();


    public static Map<String,TreeMap<Long, Long>> timeRecoredMapTree=new ConcurrentHashMap<>();


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
         String methodName = invocation.getMethodName();

         String name="$echo";
        long startTime = System.currentTimeMillis();

        Result invoke = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();
        TreeMap<Long, Long> treeMap = timeRecoredMapTree.get(methodName);
        long result=(endTime-startTime);
        if (!name.equals(methodName)){
            if (CollectionUtils.isEmpty(treeMap)){
                treeMap=new TreeMap<>(Comparator.naturalOrder());
            }
            Long aLong = treeMap.get(result);
            if (null==aLong){
                treeMap.put(result,1L);
            }else {
                treeMap.put(result,aLong+1);
            }
            timeRecoredMapTree.put(methodName,treeMap);
        }
        return invoke;
    }
}
